package com.sfy.lotterysystem.controller;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sfy.lotterysystem.dto.LoginRequest;
import com.sfy.lotterysystem.entity.User;
import com.sfy.lotterysystem.repository.UserRepository;
import com.sfy.lotterysystem.service.CaptchaService;
import com.sfy.lotterysystem.util.JwtUtil;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private final CaptchaService captchaService;
    private final UserRepository userRepository;

    public UserController(CaptchaService captchaService, UserRepository userRepository) {
        this.captchaService = captchaService;
        this.userRepository = userRepository;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginRequest req) {
        Map<String, Object> result = new HashMap<>();
        // 校验验证码
        boolean valid = captchaService.validateCaptcha(req.getCaptchaUuid(), req.getCaptcha());
        if (!valid) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return result;
        }
        // 校验用户名密码
        User dbUser = userRepository.findByUsername(req.getUsername());
        if (dbUser == null || !dbUser.getPassword().equals(req.getPassword())) {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
        } else {
            String token = JwtUtil.generateToken(dbUser.getUsername());
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("token", token);
        }
        return result;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        if (userRepository.findByUsername(user.getUsername()) != null) {
            result.put("success", false);
            result.put("message", "用户名已存在");
        } else {
            user.setCreateTime(new Date());
            userRepository.save(user);
            result.put("success", true);
            result.put("message", "注册成功");
        }
        return result;
    }
}